<template>
  <div class="change-password-container">
    <el-card class="password-card" header="修改密码">
      <el-form
          ref="passwordForm"
          :model="formData"
          :rules="rules"
          label-width="120px"
          label-position="right"
      >
        <el-form-item label="原密码" prop="oldPassword">
          <el-input
              v-model="formData.oldPassword"
              type="password"
              placeholder="请输入原密码"
              show-password
          />
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input
              v-model="formData.newPassword"
              type="password"
              placeholder="请输入新密码（至少6位字符）"
              show-password
          />
        </el-form-item>

        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input
              v-model="formData.confirmPassword"
              type="password"
              placeholder="请再次输入新密码"
              show-password
          />
        </el-form-item>

        <el-form-item class="button-group">
          <el-button type="primary" @click="handleSubmit">保存</el-button>
          <el-button @click="handleCancel">退出</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import {reactive, ref} from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
// pinia使用
import { userStore } from '/src/components/store/index.js'
import axios from "axios";
import router from "@/components/router/index.js";
import request from "@/utils/request.js";
const userItemStore = userStore();

// 表单数据
const formData = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单引用
const passwordForm = ref(null)

// 验证规则
const validateOldPassword = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入原密码'))
  } else {
    callback()
  }
}

const validateNewPassword = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入新密码'))
  } else if (value.length < 6) {
    callback(new Error('密码长度不能少于6位'))
  } else {
    callback()
  }
}

const validateConfirmPassword = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请再次输入新密码'))
  } else if (value !== formData.value.newPassword) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const rules = {
  oldPassword: [
    { validator: validateOldPassword, trigger: 'blur' }
  ],
  newPassword: [
    { validator: validateNewPassword, trigger: 'blur' }
  ],
  confirmPassword: [
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

const handleSubmit = async () => {
  try {
    const valid = await passwordForm.value.validate();
    if (!valid) {
      ElMessage.warning('请填写正确的表单信息');
      return;
    }

    await ElMessageBox.confirm('确定要修改密码吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    // 验证原密码
    const checkResp = await request.post(`/personalProfile/checkPassword`, {
      id: userItemStore.user.id,
      password: formData.value.oldPassword
    });

    if (checkResp.data !== true) {
      ElMessage.error("原密码输入错误！");
      return;
    }

    // 修改密码
    const modifyResp = await request.put(`/personalProfile/modifyPassword`, {
      id: userItemStore.user.id,
      password: formData.value.newPassword
    });

    ElMessage.success(modifyResp.data);
    router.push('/main');
    passwordForm.value.resetFields();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data);
    }
  }
};

// 取消操作
const handleCancel = () => {
    // 这里可以添加页面跳转逻辑
    router.push('/main')
    passwordForm.value.resetFields()
}
</script>

<style scoped>
.change-password-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f7fa;
}

.password-card {
  width: 500px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.button-group {
  display: flex;
  justify-content: flex-end;
  margin-top: 30px;
}

.el-form-item {
  margin-bottom: 22px;
}
</style>